package com.fingard.dsp.bank.directbank.dbs01;

import net.sf.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

/**
 * Created by F on 2018/7/12.
 */
public class DBS01Balance extends DBS01Base implements IBalance {

    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        return "1".equals(getBankConfig().getValueAsString("channelFlag"))?d7506BalQryApi(p_req7506):d7506BalQryFile(p_req7506);
    }

    /**
     * api方式
     * @param p_req7506
     * @throws Exception
     */
    private RetAts7506BalQry d7506BalQryApi(Req7506BalQry p_req7506) throws Exception{
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        RetAtsBalDetail detail = new RetAtsBalDetail();
        while(p_req7506.readRecord()) {

            String date=Format.DateTimeSSSFormat.format(new Date());//yyyy-MM-dd HH:mm:ss SSS
            StringBuilder sb2=new StringBuilder(date.replaceAll(" ",""));
            sb2.insert(10,"T").insert(19,".");

            JSONObject header = new JSONObject();
            header.put("msgId", p_req7506.reqHeader.transSeqID);//流水号
            header.put("orgId", bankFront.org);//机构号
            header.put("timeStamp", sb2.toString());//时间 yyyy-MM-ddTHH:mm:ss.SSS
            header.put("ctry", getBankConfig().getMapKeyByValue("cityFlag",p_req7506.readedDetail.actNum));//Country triggering the JSON
            JSONObject txnInfo = new JSONObject();
            txnInfo.put("txnType", "BLE");//Transaction type  Possible value: BLE
            JSONObject accountBalInfo = new JSONObject();
            accountBalInfo.put("accountNo", p_req7506.readedDetail.actNum);//Account number
            accountBalInfo.put("accountCcy", convertCurToBank(p_req7506.readedDetail.actCur));//Account currency
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("header",header);
            jsonObject.put("txnInfo",txnInfo);
            jsonObject.put("accountBalInfo",accountBalInfo);
            //发送请求报文
            String[] bankResult = sendToBank(jsonObject.toString(),"enquiry/v1/account/balance");

            //处理响应报文
            if (bankResult[0].length() == 0) {
                JSONObject jsonArray = JSONObject.fromObject(bankResult[1].replaceAll(" ",""));
                if(!"".equals(jsonArray.get("accountBalResponse")) && jsonArray.get("accountBalResponse")!=null){
                    JSONObject object=(JSONObject)jsonArray.get("accountBalResponse");
                    if("ACSP".equals(object.get("enqStatus"))){//查询成功
                        detail.respCode = "0";//响应码
                        detail.respInfo = "成功";//响应信息
                        detail.actCur = convertCurToATS(object.get("accountCcy").toString());//币种
                        detail.actNum = object.get("accountNo").toString();//账号
                        detail.availBal = object.get("clsAvailableBal").toString();//可用余额
                        detail.currBal = object.get("clsLedgerBal").toString();//余额
                        detail.frozenBal="";//冻结余额
                    }else {
                        detail.respCode = "-1";
                        detail.respInfo = object.get("enqStatusDescription").toString();
                    }
                }else {
                    detail.respCode = "-1";
                    detail.respInfo = "返回accountBalResponse不存在";
                }
            }else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
            retAts.writeRetDetail(detail,p_req7506.isBatch);
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 文件方式
     * @param p_req7506
     * @throws Exception
     */
    private RetAts7506BalQry d7506BalQryFile(Req7506BalQry p_req7506) throws Exception{
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        while(p_req7506.readRecord()){
            RetAtsBalDetail detail = new RetAtsBalDetail();
            String accNum = p_req7506.readedDetail.actNum;
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            boolean isFromMT942 = true;
            String dealedFile = getBankConfig().getValueAsString("DealedPath")+ File.separator+
                    Format.Date8Format.format(date)+
                    File.separator+"MT942"+File.separator+accNum+"_7506.txt";
            //由于周末也可能是工作日，所以去掉一下代码，之前往前一天遍历
            //如果当天的日间文件还没收到，就取前一工作日的日终文件的数据
//            if(!FileHelper.existFile(dealedFile)){
//                int week =calendar.get(calendar.DAY_OF_WEEK);
//                if(week==1){//星期天
//                    calendar.add(Calendar.DAY_OF_MONTH,-2);
//                    isFromMT942 =false;
//                }else if(week==2){//星期一
//                    calendar.add(Calendar.DAY_OF_MONTH,-3);
//                    isFromMT942 =false;
//                }else {
//                    calendar.add(Calendar.DAY_OF_MONTH,-1);
//                    isFromMT942 =false;
//                }
//                dealedFile = getBankConfig().getValueAsString("DealedPath")+File.separator+
//                        Format.Date8Format.format(calendar.getTime())+File.separator+
//                        "MT940"+File.separator+accNum+"_7505.txt";
//            }
            //由于法定节假日也是非工作日，要是前一工作日的日终文件取不到，就往前遍历，最多10天
            int num =0;
            while(!FileHelper.existFile(dealedFile)&&num<10){
                calendar.add(Calendar.DAY_OF_MONTH,-1);
                dealedFile = getBankConfig().getValueAsString("DealedPath")+File.separator+
                        Format.Date8Format.format(calendar.getTime())+File.separator+
                        "MT940"+File.separator+accNum+"_7505.txt";
                isFromMT942 = false;
            }
            String balanceContent = FileHelper.readFileText(dealedFile,getCharset());
            if(StringHelper.hasAnyChar(balanceContent)){
                //账号|币种|当前余额|可用余额|昨日余额(MT940)
                //账号|币种|当前余额|可用余额|期初余额|最后交易日期|文件生成时间|期初余额对应的日期(MT942)
                String[] bal  =balanceContent.split("\\|");
                detail.respCode ="0";
                detail.actNum =bal[0];
                detail.actCur =convertCurToATS(bal[1]);
                detail.currBal =bal[2];
                detail.availBal =bal[3];
                if(isFromMT942) {
                    detail.yesterdayBal = bal[4];
                }else {
                    detail.yesterdayBal = bal[2];
                }
            }else {
                detail.respCode="-1";
                detail.respInfo="文件读取异常";
            }
            retAts.writeRetDetail(detail,p_req7506.isBatch);
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
